<template>
  <div>
    <!-- 分配权限的弹层 -->
    <el-dialog title="分配权限" :visible="showAssignDialog" @close="closeAssignDialog" :close-on-click-modal="false">
      <!-- 树形权限 -->
      <el-tree ref="tree" :data="permissionData" :props="{ label: 'name' }" :default-expand-all="true"
        :show-checkbox="true" :check-strictly="true" node-key="id" v-loading="treeLoading" />

      <template #footer>
        <div style="text-align: right;">
          <el-button @click="closeAssignDialog">取消</el-button>
          <el-button type="primary" @click="assignRoles">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getPermissionListAPI } from '@/api/permission'
import { getRoleDetailAPI, assignRolesAPI } from '@/api/setting'
import { tranListToTreeData } from '@/utils'
export default {
  props: {
    showAssignDialog: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      permissionData: [], // 存储权限数据
      treeLoading: false
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 确认分配员工权限
    async assignRoles() {
      // 至少选择一个权限
      if (!this.$refs.tree.getCheckedKeys().length) {
        return this.$message.warning('至少选择一个权限')
      }
      await assignRolesAPI({
        id: this.userId,
        roleIds: this.$refs.tree.getCheckedKeys()
      })
      this.$message.success('分配成功')
      this.closeAssignDialog()
    },
    // 获取用户详细权限 - 回显权限
    async getPermissionDetail(id) {
      this.treeLoading = true
      const res = await getRoleDetailAPI(id)
      console.log('用户权限', res.data.permIds)
      this.$refs.tree.setCheckedKeys(res.data.permIds)  // 通过key设置
      this.treeLoading = false
    },
    // 获取权限列表
    async getPermissionList() {
      const { data } = await getPermissionListAPI()
      // 将数组数据转换为树形图数据
      this.permissionData = tranListToTreeData(data, '0')
      console.log('权限数据', this.permissionData)
    },
    // 关闭弹窗
    closeAssignDialog() {
      this.$emit('update:showAssignDialog', false)
    }
  }
}
</script>